package com.whty.cms.filewps.common.service.impl;

import com.qcloud.cmq.Account;
import com.qcloud.cmq.Message;
import com.qcloud.cmq.Queue;
import com.qcloud.cmq.QueueMeta;
import com.whty.cms.filewps.common.constants.Consts;
import com.whty.cms.filewps.common.service.CmqService;
import com.whty.cms.filewps.util.MemcacheUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2019/2/27 0027.
 */
@Service("cmqService1")
public class CmqServiceImpl implements CmqService {
    private static Account instance=null;

    private CmqServiceImpl() {}

    @Override
    public void createQueue(String queueName, int maxMsgHeapNum, int pollingWaitSeconds, int visibilityTimeout, int maxMsgSize, int msgRetentionSeconds, int rewindSeconds) throws Exception {
        QueueMeta meta = new QueueMeta();
        CmqServiceImpl.getInstance().createQueue(queueName, meta);
    }

    @Override
    public String sendMsg(String queueName, String msg) throws Exception {
        Queue queue = CmqServiceImpl.getInstance().getQueue(queueName);
        return queue.sendMessage(msg);
    }

    @Override
    public Message receiveMessage(String queueName, int pollingWaitSeconds) throws Exception {
        Queue queue = CmqServiceImpl.getInstance().getQueue(queueName);
        Message message = queue.receiveMessage(pollingWaitSeconds);
        return message;
    }

    @Override
    public List<Message> batchreceiveMessage(String queueName, int numOfMsg, int pollingWaitSeconds) throws Exception {
        Queue queue = CmqServiceImpl.getInstance().getQueue(queueName);
        return queue.batchReceiveMessage(numOfMsg,pollingWaitSeconds);
    }

    @Override
    public void deleteMsg(String queueName, String receiptHandle) throws Exception {
        Queue queue = CmqServiceImpl.getInstance().getQueue(queueName);
        queue.deleteMessage(receiptHandle);
    }

    @Override
    public void batchDeleteMsg(String queueName, List<String> receiptHandle) throws Exception {
        Queue queue = CmqServiceImpl.getInstance().getQueue(queueName);
        queue.batchDeleteMessage(receiptHandle);
    }

    public static Account getInstance() {
        if(instance==null){
            synchronized(CmqServiceImpl.class){
                if(instance == null){
                    instance = new Account( MemcacheUtil.getDatabaseObj(Consts.CMQ_ENDPOINT), MemcacheUtil.getDatabaseObj(Consts.SECRET_ID), MemcacheUtil.getDatabaseObj(Consts.SECRET_KEY));
                }
            }
        }
        return instance;
    }
}
